<?php

namespace App\Http\Controllers\Api\v1;

use App\Models\SiteConfig;
use Illuminate\Http\Request;

class SiteConfigController extends BaseController
{
    /**
     * Instanceof menu
     *
     * @var SiteConfig
     */
    private $model;


    /**
     * SiteConfigController constructor.
     * @param SiteConfig $model
     */
    public function __construct(SiteConfig $model)
    {
        $this->model = $model;
        $this->middleware('jwt.auth', ['except' => ['index']]);
        $this->middleware('jwt.refresh', ['except' => ['index']]);
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        $config = $this->model->filter($request->all())->get()->toArray();
        $configData = [];
        foreach ($config as $detail) {
            $configData[$detail['name']] = $detail['value'];
        }
        return $this->response->array($configData);
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function update(Request $request)
    {
        $data = $request->all();
        $editData = [];
        foreach ($data as $k => $v) {
            $editData[] = [
                'name' => $k,
                'value' => is_array($v) ? json_encode($v) : $v
            ];
        }
        // 查询数据库中是否有配置
        $saved = $this->model->query()->pluck('name')->all();
        $newData = collect($editData)->filter(function ($value, $key) use ($saved) {
            return !in_array($value['name'], $saved);
        })->toArray();
        $editData = collect($editData)->reject(function ($value, $key) use ($saved) {
            return !in_array($value['name'], $saved);
        })->toArray();
        if ($newData) {
            $this->model->query()->insert($newData);
        }
        $this->model->updateBatch($editData);
        return $this->response->array($data);
    }
}